package com.gykj.admin.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gykj.admin.common.entity.User;
import com.gykj.admin.common.entity.UserRole;
import com.gykj.admin.mapper.UserRoleMapper;
import com.gykj.admin.service.UserService;

/**
 * Created by rohto.li on 2017/11/03.
 */
@Service("userService")
@Cacheable(value = "redis", keyGenerator = "cacheKeyGenerator")
public class UserServiceImpl extends BaseService<User> implements UserService{
    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public PageInfo<User> selectByPage(User user, int start, int length) {
        int page = start/length+1;
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotEmpty(user.getUserNameEg())) {
            criteria.andLike("userNameEg", "%" + user.getUserNameEg() + "%");
        }
        if (user.getId() != null) {
            criteria.andEqualTo("id", user.getId());
        }
        if (user.getIsValid() != null) {
            criteria.andEqualTo("is_valid", user.getIsValid());
        }
        //分页查询
        PageHelper.startPage(page, length);
        List<User> userList = selectByExample(example);
        return new PageInfo<>(userList);
    }

    @Override
    public User selectByUsername(String username) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userNameEg",username);
        List<User> userList = selectByExample(example);
        if (userList.size() > 0) {
            return userList.get(0);
        }
            return null;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED,readOnly=false,rollbackFor={Exception.class})
    public void deleteUser(Integer userid) {
        //删除用户表
        mapper.deleteByPrimaryKey(userid);
        //删除用户角色表
        Example example = new Example(UserRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userid);
        userRoleMapper.deleteByExample(example);
    }

	@Override
	public List<User> queryUserListWithSelected(Integer uid) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        
        if (uid != null) {
            criteria.andEqualTo("id", uid);
        }
		return selectByExample(example);
	}
}
